from utils.title_level.title_pipeline_level import get_title_count
from utils.title_level.title_md_level import title_change
from utils.table_merge.table_pipeline_merge import table_pipeline_change
from utils.table_merge.table_md_merge import table_md_change
from utils.title_level.title_re import first_level
def get_first_title(pdf_type:str=r''):
    for i in first_level:
        if i["pdf_type"] == pdf_type:
            return i["pattern"]

def title_and_table_change(pipe_result,local_image_dir,image_dir,start_page:int = 1,pdf_type:str=r''):
    """
    进行标题分级处理和表格合并处理

    参数：
    pipe_result ():pipeline以后的结果
    mage_dir (str):markdown的图像存储路径
    start_page (int): 从pdf第几页开始处理

    返回值: md_content
    md_content (str):转换为符合markdown规则的字符串
    """

    # 标题第一次遍历：获取标题目录,确认一级标题
    if pdf_type:
        # 获取一级标题
        first_level_pattern = get_first_title(pdf_type)
        # 获取标题列表
        title_dict,_ = get_title_count(pipe_result._pipe_res['pdf_info'],start_page)
    else:
        title_dict,first_level_pattern = get_title_count(pipe_result._pipe_res['pdf_info'],start_page)
    for key,_ in title_dict.items():
        if key == first_level_pattern:
            title_dict[key]['level'] = 1
            break
    
    # 对跨页不超过大小小于max_height的表格进行
    # pipe_result._pipe_res = table_pipeline_change(pipe_result._pipe_res,local_image_dir)
    # 转换为markdown语法
    # print(title_dict)
    # print(first_level_pattern)
    md_content = pipe_result.get_markdown(image_dir)

    # 标题再处理
    if title_dict:
        md_content = title_change(md_content,title_dict,first_level_pattern)
    else:
        print('无标题')
    # 表格md处理
    md_content = table_md_change(md_content)
    return md_content  